import { computed, ComputedRef, reactive, ref, unref, Ref, watch } from 'vue'
import type { ElPagination } from 'element-plus'
import { useScopeEvent } from '/@/hooks/useScopeEvent'

export function usePage(getProps: ComputedRef<YTableProps>) {

  const socpeEvents = useScopeEvent()


  const pageConfig = computed(() => getProps.value.pageConfig)
  const currentPage = ref(1)
  const pageSize = ref(getProps.value.pageConfig?.size || 100)
  const totalCount = ref(0)

  const pagerProps = computed(() => ({
    currentPage: unref(currentPage),
    pageSize: unref(pageSize.value),
    pageSizes: pageConfig.value?.sizes || [100, 200, 300, 400, 500],
    layout: 'total, sizes, prev, pager, next',
    total: unref(totalCount),
    'onUpdate:current-page': (currPage: number) => {
      currentPage.value = currPage
    },
    'onUpdate:page-size': (size: number) => {
      pageSize.value = size;
    },
    'onPrev-click': () => { },
    'onNext-click': () => { },
  }))

  const isPagination = computed(() => getProps.value.remoteConfig && getProps.value.pageConfig !== false)

  const loadedCallback = (result: YTableRemoteResult) => {
    totalCount.value = result.totalCount
  }

  const triggerLoad = () => {
    socpeEvents.emit('loadData')
  }

  watch(currentPage, () => triggerLoad())
  watch(pageSize, () => triggerLoad())

  socpeEvents.on('loadDataBefore', params => {
    Object.assign(params, {
      pageIndex: currentPage.value,
      pageSize: pageSize.value
    })
  })

  return {
    isPagination,
    pagerProps,
    loadedCallback
  }
}